import 'dart:io';

import 'package:example/components/progress_bar_dialog.dart';
import 'package:example/edited_data_controller.dart';
import 'package:example/pages/full_screen_video_player.dart';
import 'package:example/utils/collection_utils.dart';
import 'package:example/video_editor/video_editor_tool_bar.dart';
import 'package:example/video_editor/video_editor_view_model.dart';
import 'package:example/video_editor/view_model_extension.dart';
import 'package:example/video_player/video_player_view_model.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:jui/jui.dart';
import 'package:video_trimmer/video_trimmer.dart';
import 'package:get/get.dart';
import 'package:zz_video_maker/zz_video_maker.dart';

import '../video_player/video_player.dart';

class VideoEditorPage extends StatefulWidget {
  final bool isAsset;
  final String path;
  const VideoEditorPage({super.key, required this.isAsset, required this.path});

  @override
  State<VideoEditorPage> createState() => _VideoEditorPageState();
}

class _VideoEditorPageState extends State<VideoEditorPage> {
  late VideoEditorViewModel viewModel =
      Get.put(VideoEditorViewModel(isAsset: widget.isAsset, path: widget.path));
  final Trimmer _trimmer = Trimmer();

  @override
  void initState() {
    _initVideoPlayerController();

    super.initState();
  }

  void _initVideoPlayerController() {
    _trimmer
        .loadVideo(
      videoFile: File(''),
    )
        .then((_) {
      // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
      setState(() {});
    });
  }

  @override
  void dispose() {
    _trimmer.videoPlayerController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("VideoEditorPage"),
        actions: [
          TextButton(
            onPressed: () {
              Get.to(FullScreenVideoPlayer(
                  videoPath: "$appDirectoryPath/result.mp4"));
            },
            child: Text('播放'),
          ),
          TextButton(
            onPressed: () {
              viewModel.vmsdkWidget.generateVideoFromObject(
                  viewModel.allEditedData!, (status, progress) {
                viewModel.progress.value = progress;
                viewModel.generateStatus.value = status;
                print(status);
                print(progress);
              });
            },
            child: Text('生成'),
          ),
          TextButton(
            onPressed: () async {
              var res = parseAllEditedDataToJSON(viewModel.allEditedData!);
              var file = File("$appDirectoryPath/last.json");
              await file.writeAsString(res);
            },
            child: Text('保存'),
          ),
        ],
      ),
      body: SafeArea(
          child: Stack(
        children: [
          viewModel.vmsdkWidget,
          GetBuilder<VideoEditorViewModel>(
              id: EditedDataController.initializedDataId,
              builder: (_) {
                if (!viewModel.initializedData) {
                  return const Text('初始化中');
                }
                return Stack(
                  children: [
                    const VideoPlayerWidget(),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const SizedBox(height: 44, child: VideoEditorToolBar()),
                        SizedBox(
                          height: 88,
                          child: SingleChildScrollView(
                            scrollDirection: Axis.horizontal,
                            child: Obx(() {
                              var editedMediaList =
                                  viewModel.allEditedData!.editedMediaList;
                              return Stack(
                                children: [
                                  Row(
                                    children:
                                        editedMediaList.mapIndex((e, index) {
                                      var isSelected =
                                          viewModel.currentIndex.value == index;
                                      return bottomItem(index, isSelected, e);
                                    }).toList(),
                                  ),
                                  ...List.generate(editedMediaList.length - 1,
                                      (index) {
                                    var data = editedMediaList[index];
                                    var width = 33.0;
                                    var itemWidth = 88.0;
                                    var has = data.transition != null;
                                    return Positioned(
                                        left: index * itemWidth +
                                            itemWidth -
                                            width * 0.5,
                                        top: (itemWidth - width) * 0.5,
                                        child: !has
                                            ? Container()
                                            : JUIButton(
                                                onPressed: () {
                                                  viewModel.transition(context,
                                                      index: index);
                                                },
                                                child: Container(
                                                  width: width,
                                                  height: width,
                                                  decoration: BoxDecoration(
                                                      color: Colors.white,
                                                      borderRadius:
                                                          BorderRadius.circular(
                                                              5)),
                                                  child: const Icon(
                                                    Icons.animation_rounded,
                                                  ),
                                                ),
                                              ));
                                  })

                                  // GetBuilder<VideoEditorViewModel>(
                                  //   id: 'bottomTransition',
                                  //   builder: (controller) {
                                  //     return Stack(
                                  //       children: viewModel
                                  //           .allEditedData!.editedMediaList
                                  //           .mapIndex((e, index) {
                                  //         var isSelected =
                                  //             viewModel.currentIndex.value ==
                                  //                 index;
                                  //         return Positioned(
                                  //             left: index * 88 + 66,
                                  //             child: Container(
                                  //               color: Colors.red,
                                  //               width: 44,
                                  //               height: 22,
                                  //             ));
                                  //       }).toList(),
                                  //     );
                                  //   },
                                  // )
                                ],
                              );
                            }),
                          ),
                        ),
                      ],
                    ),
                    Obx(() => Visibility(
                          visible: viewModel.generateStatus.value ==
                              EGenerateStatus.encoding,
                          child: CoolPercentageProgressBarDialog(
                              percentage: viewModel.progress.value * 100 - 1),
                        ))
                  ],
                );
              }),
        ],
      )),
    );
  }

  InkWell bottomItem(int index, bool isSelected, EditedMedia e) {
    return InkWell(
      onTap: () {
        viewModel.setCurrentIndex(index);
      },
      child: Container(
        width: 88,
        height: 88,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          image: DecorationImage(
            image: FileImage(File(e.coverImage!)),
            fit: BoxFit.cover,
          ),
        ),
        child: Stack(
          fit: StackFit.expand,
          children: [
            if (isSelected)
              Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: TextButton(
                  onPressed: () {
                    if (viewModel.currentEditedMedia?.mediaData.type ==
                        EMediaType.image) {
                      var path =
                          viewModel.currentEditedMedia?.mediaData.absolutePath;
                      if (path == null) {
                        return;
                      }
                      _cropImage(path);
                    } else {
                      viewModel.updateTrimmer(true);
                    }
                  },
                  child: const Text(
                    "编辑",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Future<void> _cropImage(String path) async {
    final croppedFile = await ImageCropper().cropImage(
      sourcePath: path,
      compressFormat: ImageCompressFormat.jpg,
      compressQuality: 100,
      uiSettings: [
        AndroidUiSettings(
            toolbarTitle: '裁剪',
            toolbarColor: Colors.deepOrange,
            toolbarWidgetColor: Colors.white,
            initAspectRatio: CropAspectRatioPreset.original,
            lockAspectRatio: false),
        IOSUiSettings(
          title: '裁剪',
        ),
      ],
    );

    if (croppedFile != null) {
      var croppedPath = croppedFile.path;
      var editedMedia = viewModel.currentEditedMedia;
      if (editedMedia == null) {
        return;
      }
      editedMedia.mediaData.scaledPath = croppedPath;
      var videoPath = await extractVideoFromImageMedia(editedMedia);
      var res = await videoRealWidthHeight(videoPath);
      if (res != null) {
        editedMedia.mediaData.width = res.$1;
        editedMedia.mediaData.height = res.$2;
        viewModel.updatePlayer();
      }
    }
  }
}
